package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomException;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.DishMapper;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品
 */
@Slf4j
@Service
//开启事务
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 新增菜品，同时保存对应的口味信息
     *
     * @param dishDto
     */
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //因为DishDto是包含了Dish的信息，所以可以先存Dish信息到Dish表中，DishDto扩展的数据可以下一步再存
        //为什么这里传dishDto可以，因为DishDto是Dish的子类
        dishService.save(dishDto);
        //拿ID和口味List，为存DishDto做准备
        Long dishId = dishDto.getId();
        List<DishFlavor> flavor = dishDto.getFlavors();
        //遍历 set入id值到菜品口味表中
        for (DishFlavor dishFlavors : flavor) {
            dishFlavors.setDishId(dishId);
        }
        //saveBatch是批量集合的存储
        dishFlavorService.saveBatch(flavor);

        //删除缓存中某一个菜品分类，把一整个 “粤菜” 都删掉
        stringRedisTemplate.delete("dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus());

    }

    /**
     * 根据id查询菜品信息和口味信息
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品信息获得dish对象
        Dish dish = this.getById(id);

        DishDto dishDto = new DishDto();
        //拷贝dish对象的属性到dishDto
        BeanUtils.copyProperties(dish, dishDto);

        //查询当前菜品对应的口味信息，从dish_flavor表查询
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);

        //再把查询到的口味信息set进去dishDto中，返回该对象
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    /**
     * 修改菜品信息，同时更新对应的口味信息
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //更新dish表的基本信息
        this.updateById(dishDto);

        //清理当前菜品对应口味数据----dish_flavor表的delete操作
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //添加当前提交过来的口味数据-----dish_flavor表的insert操作
        //这里只是封装了name和value，并没有把dish_id放回去
        List<DishFlavor> flavors = dishDto.getFlavors();
        //所以我们需要遍历flavors来设置dish_id
        flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);

//        log.info("dishDto:{}", dishDto);

        //删除缓存中某一个菜品分类，把一整个 “粤菜” 都删掉
        stringRedisTemplate.delete("dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus());

    }

    /**
     * 单个/批量停售菜品
     *
     * @param ids
     * @return
     */
    @Override
    public boolean updateStatusStopByIds(List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(0);
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId, id);
            boolean result = dishService.update(dish, queryWrapper);
            if (!result) {
                return false;
            }
        }
        return true;
    }

    /**
     * 单个/批量起售菜品
     *
     * @param ids
     * @return
     */
    @Override
    public boolean updateStatusStartByIds(List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(1);
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId, id);
            boolean result = dishService.update(dish, queryWrapper);
            if (!result) {
                return false;
            }
        }
        return true;
    }

    /**
     * 删除菜品，同时删除菜品与菜品口味的关系
     *
     * @param ids
     */
    @Override
    //开启事务
    @Transactional
    public void removeWithFlavor(List<Long> ids) {
        //select count(*) from dish where id in (1,2,3) and status = 1
        //查询菜品是否为停售状态，确认是否可以删除
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);
        queryWrapper.eq(Dish::getStatus, 1);

        //如果不能删除，则抛出业务异常
        int count = (int) this.count(queryWrapper);
        if (count > 0) {
            throw new CustomException("菜品正在售卖中，不能删除！");
        }

        //如果可以删除，先逻辑删除菜品表 ---- dish
        this.removeByIds(ids);

        //delete from dish_flavor where dish_id in (1,2,3)
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(DishFlavor::getDishId, ids);
        //再暴力删除菜品口味关系表 ---- dish_flavor
        dishFlavorService.remove(lambdaQueryWrapper);

    }

    /**
     * 把菜品数据缓存到Redis中
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishDto> listByRedis(Dish dish) {

        List<DishDto> dishDtoList = null;

        //动态构造key，dish_1397844391040167938_1
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从Redis中获取缓存数据
        String json = stringRedisTemplate.opsForValue().get(key);
        dishDtoList = JSON.parseObject(json, new TypeReference<List<DishDto>>() {
        });

//        log.info("dishDtoList:{}", dishDtoList);

        //判断dishDtoList是否为空
        if (dishDtoList != null) {
            //如果存在，则直接返回，无需查询数据库
            return dishDtoList;
        }

        //如果不存在,需要查询数据库
        //设置构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //起售状态（status为1）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //按sort升序，同级的按更新时间降序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //把其他属性拷贝到dishDto
            BeanUtils.copyProperties(item, dishDto);
            //获取每个菜品的分类id
            Long categoryId = item.getCategoryId();
            //根据分类id去查分类的名称
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                //把categoryName属性放回到dishDto对象中去
                //后台需求完成
                dishDto.setCategoryName(categoryName);
            }
            //前台需求
            //获取当前菜品的id
            Long dishId = item.getId();
            //通过菜品的id来查询出菜品口味的list数据
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            //再把菜品口味信息设置回dishDto对象中去，供前台使用口味信息的数据
            //前台需求完成
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //将dishDtoList转为JSON并存储到Redis中，因为String类型是不能直接存List集合
        String dishDtoJson = JSON.toJSONString(dishDtoList);
        //将查询到菜品数据缓存到Redis当中
        stringRedisTemplate.opsForValue().set(key, dishDtoJson, 60, TimeUnit.MINUTES);

        return dishDtoList;
    }

}
